import React, { useState } from 'react';
import { request } from '@/api/request';
import { useTranslation } from 'react-i18next';
import { getDynamicFonts } from '@/utils/fontUtils';

// 新增：重置密码表单组件
const ResetPasswordForm: React.FC = () => {
    const { t, i18n } = useTranslation();
    const dynamicFonts = getDynamicFonts(i18n);
    const [password, setPassword] = useState('');
    const [confirmPassword, setConfirmPassword] = useState('');
    const [showPassword, setShowPassword] = useState(false);
    const [showConfirmPassword, setShowConfirmPassword] = useState(false);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState('');
    // 获取 reset_password_token
    const getToken = () => {
        const params = new URLSearchParams(window.location.search);
        let token = params.get('reset_password_token');
        if (!token && window.location.hash) {
            const hashParams = new URLSearchParams(window.location.hash.split('?')[1]);
            token = hashParams.get('reset_password_token');
        }
        return token || '';
    };
    const resetToken = getToken();

    const handleSubmit = async (e: React.FormEvent) => {
        e.preventDefault();
        setError('');
        if (!password || !confirmPassword) {
            setError(t('setPassword.errors.passwordRequired'));
            return;
        }
        if (password !== confirmPassword) {
            setError(t('setPassword.errors.passwordMismatch'));
            return;
        }
        setLoading(true);
        try {
            // 这里直接用 request 复用全局 token 拦截器
            const res = await request.post(
                '/api/visitor/reset-password',
                {
                    reset_password_token: resetToken,
                    newPassword: password,
                    confirmPassword: confirmPassword,
                },
            );
            if (res.data.success) {
                window.location.replace('/'); // 跳转首页，不留历史记录
            } else {
                setError(res.data.message || t('setPassword.errors.resetFailed'));
            }
        } catch (err: any) {
            setError(err?.response?.data?.message || t('setPassword.errors.networkError'));
        } finally {
            setLoading(false);
        }
    };

    return (
        <form className="simple_form new_user" id="new_user" autoComplete="off" onSubmit={handleSubmit}>
            <input type="hidden" name="_method" value="put" autoComplete="off" />
            <input type="hidden" name="user[reset_password_token]" value={resetToken} />
            <div className="form-inputs mb-3 px-0 md:px-10">
                {/* 密码输入框 */}
                <div className="mt-6 w-full flex-col justify-start items-start gap-1.5 inline-flex">
                    <div className="self-stretch flex-col justify-start items-start gap-1.5 flex relative">
                        <div className="w-5 h-5 absolute top-[13px] left-[10px] flex items-center justify-center text-neutral-400">
                            <i className="fa fa-lock"> </i>
                        </div>
                        <div className="w-5 h-5 absolute top-[13px] right-[10px] flex items-center justify-center text-neutral-400 cursor-pointer" onClick={() => setShowPassword(v => !v)}>
                            <i className={`fas fa-${showPassword ? 'eye-slash' : 'eye'}`} style={{ color: "rgb(255,255,255)" }}></i>
                        </div>
                        <input
                            className=" required w-full self-stretch pl-10 pr-10 px-3.5 py-2.5 rounded-lg shadow-2xs border border-[#363636] text-white bg-stone-900"
                            required
                            aria-required="true"
                            placeholder={t('setPassword.password')}
                            type={showPassword ? 'text' : 'password'}
                            name="user[password]"
                            id="user_password"
                            value={password}
                            onChange={e => setPassword(e.target.value)}
                            style={{ fontFamily: dynamicFonts.font3 }}
                        />
                    </div>
                </div>
                {/* 确认密码输入框 */}
                <div className="w-full mt-6 flex-col justify-start items-start gap-1.5 inline-flex">
                    <div className="self-stretch flex-col justify-start items-start gap-1.5 flex relative">
                        <div className="w-5 h-5 absolute top-[13px] left-[10px] flex items-center justify-center text-neutral-400">
                            <i className="fa fa-lock"></i>
                        </div>
                        <div className="w-5 h-5 absolute top-[13px] right-[10px] flex items-center justify-center text-neutral-400 cursor-pointer" onClick={() => setShowConfirmPassword(v => !v)}>
                            <i className={`fas fa-${showConfirmPassword ? 'eye-slash' : 'eye'}`} style={{ color: "rgb(255,255,255)" }}></i>
                        </div>
                        <input
                            className="password required w-full self-stretch pl-10 pr-10 px-3.5 py-2.5 rounded-lg shadow-2xs border border-[#363636] text-white bg-stone-900"
                            required
                            aria-required="true"
                            placeholder={t('setPassword.confirmPassword')}
                            type={showConfirmPassword ? 'text' : 'password'}
                            name="user[password_confirmation]"
                            id="user_password_confirmation"
                            value={confirmPassword}
                            onChange={e => setConfirmPassword(e.target.value)}
                            style={{ fontFamily: dynamicFonts.font3 }}
                        />
                    </div>
                </div>
            </div>
            {error && <div className="text-red-500 text-sm mb-2 mt-2">{error}</div>}
            <button
                name="button"
                type="submit"
                className="w-full mt-4 px-4 py-3 bg-[#E75275] rounded-[10px] border border-[#E75275] justify-center items-center gap-2 inline-flex text-white disabled:opacity-60"
                id="signup-btn"
                disabled={loading}
                style={{ fontFamily: dynamicFonts.font3 }}
            >
                {loading ? t('setPassword.submitting') : t('setPassword.submit')}
            </button>
        </form>
    );
};

const SetPassWord: React.FC = () => {
    const { t, i18n } = useTranslation();
    const dynamicFonts = getDynamicFonts(i18n);

    return (
        <div style={{ width: '100%' }} className="min-h-screen bg-app-dark text-white flex w-full min-w-0 flex-col">
            {/* 主内容区 */}
            <div className="flex w-full min-w-0 flex-1">
                <div className="flex-1 w-full">
                    {/* 重置密码表单 */}
                    <div className="flex flex-col justify-center py-1 sm:px-6 lg:px-8 bg-neutral-950">
                        <div className="sm:mx-auto sm:w-full sm:max-w-md relative z-10 text-center px-4 sm:px-10"></div>
                        <div className="p-4 sm:p-6 mt-10 sm:mx-auto sm:w-full sm:max-w-[480px] relative z-10">
                            <div style={{ fontFamily: dynamicFonts.font4 }} className="bg-stone-900 p-4 sm:p-6 shadow-2xs rounded-lg border border-neutral-700 text-center">
                                <h1 className="text-white text-2xl font-semibold leading-loose mb-3" >{t('setPassword.title')}</h1>
                                <div className="px-2 sm:px-6 text-center text-neutral-400 text-sm font-medium leading-tight">{t('setPassword.subtitle')}</div>
                                <ResetPasswordForm />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            {/* 登录弹窗 */}
            {/* {loginState.showLoginModal && (
                <LoginModal
                    show={loginState.showLoginModal}
                    onClose={() => setLoginState(s => ({ ...s, showLoginModal: false }))}
                    activeTab={activeTab}
                    onLoginSuccess={() => setLoginState(s => ({ ...s, showLoginModal: false }))}
                />
            )} */}
        </div>
    );
};

export default SetPassWord;